<?php

define('PHPFOX', true);
define('PHPFOX_DS', DIRECTORY_SEPARATOR);
define('PHPFOX_DIR', dirname(__FILE__) . PHPFOX_DS);
require_once PHPFOX_DIR . 'module' . PHPFOX_DS . 'topcmmchat' . PHPFOX_DS . 'include' . PHPFOX_DS . 'service' . PHPFOX_DS . 'functions.class.php';
if (!function_exists('json_decode'))
{
    require (PHPFOX_DIR . 'module' . PHPFOX_DS . 'topcmmchat' . PHPFOX_DS . 'include' . PHPFOX_DS . 'service' . PHPFOX_DS . 'JSON.php');
}
define('CACHE_PATH',PHPFOX_DIR.'file/cache/');

class Topcmmchat_Service_Topcmmchat extends Phpfox_Service
{
    private $clientUrl = 'http://www.123flashchat.com';
    private $clientSize = array();
    private $serverPath = '';
    private $group = 'dafault';
    private $roomName = 'Lobby';

    function validate_server($host, $port)
    {
        $s_own_loc = 0;
        return $s_own_loc;
    }
    function validate_client($client_loc)
    {
        $c_own_loc = 1;
		$swf = $client_loc . '123flashchat.swf';
		$headers =	topcmmRequestRemote::requestRemote($swf,0);
		if($headers){
			if(substr($headers, 9, 3) == '200'){
				$c_own_loc = 0;
			}
			//$c_own_loc = (substr($headers, 9, 3) == '200') ? 0 : 1;
		}//echo $c_own_loc; var_dump($c_own_loc);echo "<br />";
        return $c_own_loc;
    }

    public function getSettings()
    {
        $sCacheId = $this->cache()->set('chat_settings');
        if (!($aRow = $this->cache()->get($sCacheId)))
        {
            $sTable = Phpfox::getT('chat_settings');
            $aRows = $this->database()->select('*')
                    ->from($sTable)
                    ->where('id = 1')
                    ->execute('getRows');
            $aRow = $aRows[0];
            $this->cache()->save($sCacheId, $aRow);
        }
        return $aRow;
    }

    public function Chat_Service_Chat()
    {
    }

 
    public function getClientUrl(){
        $aSettings = $this->getSettings();
        $url = 'http;//www.123flashchat.com/';
        if ($aSettings['fc_extendserver'] == 0){
            $server_host = $aSettings['fc_server_host'];            
            $server_host = str_replace('http://','',$server_host);
            $server_host = str_replace('/','',$server_host);
        	if ($server_host == '127.0.0.1' || $server_host == 'localhost')
            {
                $server_host = $_SERVER['SERVER_NAME'];
            }
            $url = 'http://' . $server_host;
            $url .= ':' . $aSettings['fc_http_port'] . '/';

            $this->serverPath = $url;

            if ($aSettings['fc_client_loc'] != '')
            {
                $url = $aSettings['fc_client_loc'];
            }
            $url .= '123flashchat.swf?';
            if ($server_host != ''){
                $url .= 'init_host=' . $server_host;
            }
            if ( $aSettings['fc_server_port'] != ''){
                $url .= '&init_port=' . $aSettings['fc_server_port'];
            }
            if(Phpfox::isUser() && $user = $this->getUser()){
                $url .= '&init_user=' . $user['full_name'] . '&init_password=' . $user['password'];
            }
        }else if ($aSettings['fc_extendserver'] == 1){
            $url = $aSettings['fc_client_loc'];
            $url = 'http://'.str_replace('http://','',$url);
            if(substr($url,-1,1) != "/"){
                $url .= '/';
            }
            $temp = $url;
            $this->serverPath = substr($temp, 0, stripos($temp, '.com') + 5);
            $urlinfo = $this->getHostParameters($url);
            parse_str($urlinfo['query']);
            $url .= '123flashchat.swf?';
            $url .= 'init_host=' . $aSettings['fc_server_host'];
            $url .= '&init_port=' . $aSettings['fc_server_port'];
            $url .= '&init_group=' . $aSettings['fc_group'];
            $this->group = $aSettings['fc_group'];
            if(Phpfox::isUser() && $user = $this->getUser()){
                $url .= '&init_user=' . $user['full_name'] . '&init_password=' . $user['password'];
            }
        }else{
            $url = 'http://free.123flashchat.com/js.php?';
            $this->serverPath = $url;
            $this->roomName = $aSettings['fc_room'];
            $url .= 'room=' . $aSettings['fc_room'];
            $url .= '&skin=' . $aSettings['fc_client_skin'];
            if ($aSettings['fc_client_lang'] != 'auto'){
                $url .= '&lang=' . $aSettings['fc_client_lang'];
            }
            if($aSettings['fc_fullscreen'] != 1){
            	$url .= '&width=' . $aSettings['fc_client_width'];
            	$url .= '&height=' . $aSettings['fc_client_height'];
            }
            
            if (Phpfox::isUser()){
                $url .= '&user=' . Phpfox::getUserBy('user_name');
            }
        }
        return $url;
    }

    function getHostParameters($client_location)
    {
        $content = topcmmRequestRemote::requestRemote($client_location,1);
        if(!empty($content))
        {
            $pattern = '|var urlValue="(.*)"|U';
            preg_match($pattern, $content, $matches);
            if(!empty($matches[1]))
            {
                $url = $matches[1];
                $urlinfo = parse_url($url);
                return $urlinfo;
            }
            else
            {
                $pattern = '|PARAM NAME=movie VALUE="(.*)"|U';
                preg_match($pattern, $content, $matches);
                if(!empty($matches[1]))
                {
                    $url = $matches[1];
                    $urlinfo = parse_url($url);
                    return $urlinfo;
                }
            }
            return false;
        }
    }

    public function getUser()
    {
        
        $user = array();
        if (Phpfox::isUser())
        {
            $u = Phpfox::getLib('phpfox.database')
                    ->select('*')
                    ->from(Phpfox::getT('user'))
                    ->where('user_id = ' . Phpfox::getUserId())
                    ->execute('getRows');
            $user = $u[0];
        }
        return $user;
    }

    public function getRooms()
    {
        if (function_exists('json_decode'))
        {
            $sCachedId = $this->cache()->set('chat_rooms');
            if (!($rooms_json = $this->cache()->get($sCachedId, 2))  || $rooms_json == "null")
            {
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver'])
                {
                    case 0:
                        $room_js = $this->serverPath . 'rooms.js';
                        if($rs = topcmmRequestRemote::requestRemote($room_js,1))
                        {
                            $rooms_json = substr($rs,10,-1);
                        }
                        break;
                    case 1:
                        $room_js = $this->serverPath . "rooms.js?group=" . $this->group;
                        if($rs = topcmmRequestRemote::requestRemote($room_js,1))
                        {
                            $rooms_json = substr($rs,10,-1);
                        }
                        break;
                    case 2:
                        break;
                }
                $this->cache()->save($sCachedId, $rooms_json);
            }
            return json_decode($rooms_json, true);
        }
        else
        {
            $srvr = new Services_JSON();
            $sCachedId = $this->cache()->set('chat_rooms');
            if (!($rooms_json = $this->cache()->get($sCachedId, 2)))
            {
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver'])
                {
                    case 0:
                        $room_js = $this->serverPath . 'rooms.js';
                        if($rs = topcmmRequestRemote::requestRemote($room_js,1))
                        {
                            $rooms_json = substr($rs,10,-1);
                        }
                        break;
                    case 1:
                        $room_js = $this->serverPath . "rooms.js?group=" . $this->group;
                        if($rs = topcmmRequestRemote::requestRemote($room_js,1))
                        {
                            $rooms_json = substr($rs,10,-1);
                        }
                        break;
                    case 2:
                        break;
                }
                $this->cache()->save($sCachedId, $rooms_json);
            }
            $temp = $srvr -> decode($rooms_json);
            $what = array();
            foreach ($temp as $nani)
            {
                array_push($what, get_object_vars($nani));
            }
            return $what;
        }
    }

    public function getUsers()
    {
        if (function_exists('json_decode'))
        {
            $sCachedId = $this->cache()->set('chat_users');
            if (!($users_json = $this->cache()->get($sCachedId, 2)) || $users_json == "null")
            {
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver'])
                {
                    case 0:
                        $users = array();
                        $rooms = $this->getRooms();
                        foreach ($rooms as $room)
                        {
                            $user_js = $this->serverPath . "roomonlineusers.js?roomid=" . $room['id'];
                            if($rs = topcmmRequestRemote::requestRemote($user_js,1))
                            {
                                $users = array_merge($users, json_decode(substr($rs,20,-1),true));
                            }
                        }
                        $users_json = json_encode($users);
                        break;
                    case 1:
                        $user_js = $this->serverPath . "roomonlineusers.js?group=" . $this->group;
                        if($rs = topcmmRequestRemote::requestRemote($user_js,1))
                        {
                            $users_json = substr($rs,20,-1);
                        }
                        break;
                    case 2:
                        $user_js = "http://free.123flashchat.com/freeroomuser.php?roomname=" . $this->roomName;
                        if($rs = topcmmRequestRemote::requestRemote($user_js))
                        {
                            foreach (explode(',', substr($rs,24,-3)) as $user)
                            {
                                $users[] = array('name' => $user);
                            }
                        }
                        $users_json = json_encode($users);
                        break;
                }
                $this->cache()->save($sCachedId, $users_json);
            }
            return json_decode($users_json, true);
        }
        else
        {
            $srvr = new Services_JSON();
            $sCachedId = $this->cache()->set('chat_users');
            if (!($users_json = $this->cache()->get($sCachedId, 2)))
            {
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver'])
                {
                    case 0:
                        $users = array();
                        $rooms = $this->getRooms();
                        foreach ($rooms as $room)
                        {
                            $user_js = $this->serverPath . "roomonlineusers.js?roomid=" . $room['id'];
                            if($rs = topcmmRequestRemote::requestRemote($user_js,1))
                            {
                                $users = array_merge($users, $srvr -> decode(substr($rs,20,-1),true));
                            }
                        }
                        $users_json = $srvr -> encode($users);
                        break;
                    case 1:
                        $user_js = $this->serverPath . "roomonlineusers.js?group=" . $this->group;
                        if($rs = topcmmRequestRemote::requestRemote($user_js,1))
                        {
                            $users_json = substr($rs,20,-1);
                        }
                        break;
                    case 2:
                        $user_js = "http://free.123flashchat.com/freeroomuser.php?roomname=" . $this->roomName;
                        if($rs = topcmmRequestRemote::requestRemote($user_js,1))
                        {
                            foreach (explode(',', substr($rs,24,-3)) as $user)
                            {
                                $users[] = array('name' => $user);
                            }
                        }
                        $users_json = $srvr -> encode($users);
                        break;
                }
                $this->cache()->save($sCachedId, $users_json);
            }
            $temp = $srvr -> decode($users_json);
            $what = array();
            foreach ($temp as $nani)
            {
                array_push($what, get_object_vars($nani));
            }
            return $what;
        }
    }

    public function getStatus(){  
	    if (function_exists('json_decode')){
            $sCachedId = $this->cache()->set('chat_status');
            if (!($status_json = $this->cache()->get($sCachedId, 2)) || $status_json == "null"){
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver']){
                    case 0:
                        $status_js = $aSettings['fc_api_url'] . 'online.js';
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1)){
                            $status_json = substr($rs,11,-1);
                        }
                        break;
                    case 1:
                        $status_js = $aSettings['fc_api_url'] . 'online.js?group=' . $aSettings['fc_group'];
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1)){
                            $status_json = substr($rs,11,-1);
                        }
                        break;
                    case 2:
                        $status_js = 'http://free.123flashchat.com/freeroomnum.php?roomname=' . $aSettings['fc_room'];
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1))
                        {
                            $status['rn'] = 'only this';
                            $status['cn'] = 'unknow';
                            $status['ln'] = substr($rs,24,-3);
                            $status_json = json_encode($status);
                        }
                        break;
                }
                $this->cache()->save($sCachedId, $status_json);
            }
            return json_decode($status_json,true);
        }else{
            $sCachedId = $this->cache()->set('chat_status');
            if (!($status_json = $this->cache()->get($sCachedId, 2))){
                $aSettings = $this->getSettings();
                switch ($aSettings['fc_extendserver']){
                    case 0:
                        $status_js = $aSettings['fc_api_url'] . 'online.js';
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1)){
                            $status_json = substr($rs,11,-1);
                        }
                        break;
                    case 1:
                        $status_js = $aSettings['fc_api_url'] . 'online.js?group=' . $aSettings['fc_group'];
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1)){
                            $status_json = substr($rs,11,-1);
                        }
                        break;
                    case 2:
                        $status_js = 'http://free.123flashchat.com/freeroomnum.php?roomname=' . $aSettings['fc_room'];
                        if($rs = topcmmRequestRemote::requestRemote($status_js,1)){
                            $status['rn'] = 'only this';
                            $status['cn'] = 'unknow';
                            $status['ln'] = substr($rs,24,-3);
                            $status_json = $srvr -> encode($status);
                        }
                        break;
                }
                $this->cache()->save($sCachedId, $status_json);
            }
            $srvr = new Services_JSON();
            $temp = $srvr -> decode($status_json);
            $arr = get_object_vars($temp);
            return $arr;
        }
    }
}
?>